package com.bum.api.web.util;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import com.bum.api.core.exp.om.Metas;
import com.bum.api.core.exp.om.Params;

public class RequestUtil {
	public static String getPath(HttpServletRequest request) {
		String path = request.getServletPath() + StringUtils.trimToEmpty(request.getPathInfo());
		if (path != null && path.startsWith("/")) {
			return path.substring(1);
		}
		return path;
	}

	public static Params getParams(HttpServletRequest request) {
		return new Params(request.getParameterMap());
	}

	public static Metas getMetas(HttpServletRequest request) {
		Metas metas = new Metas();
		metas.put(Metas.METHOD, request.getMethod());
		metas.put(Metas.USER_AGENT, request.getHeader("User-Agent"));
		metas.put(Metas.ACCEPT_ENCODING, request.getHeader("Accept-Encoding"));
		metas.put(Metas.CLIENT_IP, getClientAddress(request));

		StringBuffer url = request.getRequestURL();
		String query = request.getQueryString();
		if (query != null) {
			url.append("?").append(query);
		}
		metas.put(Metas.URL, url.toString());
		return metas;
	}

	public static String getClientAddress(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		if (ip != null) {
			ip = ip.replace(", 127.0.0.1", "");
			if (ip.indexOf(",") > -1) {
				String[] parts = ip.split(",");
				ip = parts[parts.length - 1];
			}
		}
		return ip;
	}
}
